/*
 * FileAsMsg plug-in for Miranda IM and QIP Infium.
 * Sending/receiving files via instant messaging without protocol support.
 * Homepage: http://code.google.com/p/fileasmsg/
 *
 * Copyright (c) 2008, Radist <radist.nt@gmail.com>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Name(s) of contributor(s) may not be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY Radist ''AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL Radist BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "proto.h"
#include "Sessions.h"
#include <crtdbg.h>
#include "workthread.h"
#include "plugin.h"

//Note 1: after changing this modify also FAM_HEADER_LEN macro
//Note 2: the last char should be a protocol version number
const char FAM_HEADER[] = "!#FaM%.1";
const char FAM_USERMSG[] = "\n\nPlease, install FileAsMsg plug-in from http://code.google.com/p/fileasmsg/";

const char* const PROTO_BLOCK	= ":";    //  -->
const char* const PROTO_ABORT	= "ABR!"; // <-->
const char* const PROTO_FILE	= "FIL?"; //  --> filename.ext?flags,filesize,blocksize
const char* const PROTO_ACCEPT	= "ACT!"; // <--
const char* const PROTO_REFUSE	= "REF!"; // <--
const char* const PROTO_SENT	= "ALL!"; //  -->
const char* const PROTO_RESEND	= "RSN?"; // <--  block1,block2,block3,[...]
const char* const PROTO_FINISH	= "END!"; // <--

struct msg_type_st
{
	const char* const proto_act;
	FAMMSG type;
};
const struct msg_type_st classifier[] = 
{
	{ PROTO_SENT,	FAMMSG_SENT },
	{ PROTO_RESEND,	FAMMSG_RESEND },
	{ PROTO_FILE,	FAMMSG_FILE },
	{ PROTO_ACCEPT,	FAMMSG_ACCEPT },
	{ PROTO_FINISH,	FAMMSG_FINISH },
	{ PROTO_REFUSE,	FAMMSG_REFUSE },
	{ PROTO_ABORT,	FAMMSG_ABORT },
	{ NULL, FAMMSG_INVALID }
};

const char * const commands[FAMMSG_INVALID] = 
{
	PROTO_BLOCK,		//  -->
	PROTO_ABORT,	// <-->
	PROTO_FILE,		//  -->  filename.ext?flags,filesize,blocksize
	PROTO_ACCEPT,	// <--
	PROTO_REFUSE,	// <--
	PROTO_SENT,		//  -->
	PROTO_RESEND,	// <--  block1,block2,block3,[...]
	PROTO_FINISH,	// <--
};

//See enum in TransferSession.h
const char FAM_FLAGS_MAP[] = "";

BOOL SelectFileName(bool bread, wchar_t *filename, size_t filelen);

#define SIZES_RADIX 16

inline void PrepareFAMMessage(char *buffer, const size_t buffer_len, const FAMMSG type)
{
	strcpy_s(buffer, buffer_len, FAM_HEADER);
	strcpy_s(buffer + FAM_HEADER_LEN, buffer_len - FAM_HEADER_LEN, commands[type]);
}

template<size_t _len>inline void PrepareFAMMessage(char (&buffer)[_len], const FAMMSG type)
{
	PrepareFAMMessage(buffer, _len, type);
}

template<FAMMSG type>inline char * PrepareFAMMessage(char *buffer, size_t &buffer_len)
{
	PrepareFAMMessage(buffer, buffer_len, type);
	buffer_len -= FAM_HEADER_LEN + PROTO_CMD_LEN;
	return buffer + FAM_HEADER_LEN + PROTO_CMD_LEN;
}

template<>inline char * PrepareFAMMessage<FAMMSG_BLOCK>(char *buffer, size_t &buffer_len)
{
	PrepareFAMMessage(buffer, buffer_len, FAMMSG_BLOCK);
	buffer_len -= FAM_HEADER_LEN + PROTO_BLOCK_LEN;
	return buffer + FAM_HEADER_LEN + PROTO_BLOCK_LEN;
}

void ProcessIncomingFAMMsg( HANDLE hContact, FAMMSGINFO &msg )
{
	if (*PROTO_BLOCK==*(msg.pBlob))
	{
		msg.type = FAMMSG_BLOCK;
		--msg.cbBlob;
		++msg.pBlob;
	} 
	else
	{
		for (const struct msg_type_st *centry = classifier; centry->proto_act; ++centry)
		{
			if (!strncmp(centry->proto_act, msg.pBlob, PROTO_CMD_LEN))
			{
				msg.type = centry->type;
				msg.cbBlob-=PROTO_CMD_LEN;
				msg.pBlob+=PROTO_CMD_LEN;
				break;
			}
		}
	}

	TransferSession *session = Sessions::GetInstance().Get(hContact);
	if (session)
	{
		session->ProcessMsg(msg);
	} 
	else
	{
		if (FAMMSG_FILE==msg.type)
		{
			//Process file send request
			char *es = strchr(msg.pBlob, '?'), *ns = es;

			if (es&&es>msg.pBlob&&(msg.cbBlob-(es-msg.pBlob)>5))
			{
				DWORD flags = 0;
				while (','!=*++ns)
				{
					const char *fl = strchr(FAM_FLAGS_MAP, *es);
					if (fl)
					{
						flags |= 1 << (fl - FAM_FLAGS_MAP);
					}
				}

				DWORD fsize = strtoul(ns+1, &ns, SIZES_RADIX), csize = strtoul(ns+1, &ns, SIZES_RADIX);
				if (fsize>0&&csize>0&&fsize<ULONG_MAX&&csize<=CHUNK_SIZE_MAX)
				{
					*es = 0;
					wchar_t filename[2*MAX_PATH], *f;
					if (msg.flags&DBEF_UTF)
					{
						f = _utf8decodeW(msg.pBlob);
					} 
					else
					{
						f = _a2u(msg.pBlob);
					}
					wcscpy_s(filename, f);
					_free((void*)f);
					if (SelectFileName(false, filename, sizeof(filename)/sizeof(filename[0])))
					{
						DeleteFileW(filename);
						CreateTransferer(hContact, filename, flags, fsize, csize);
					}
					else
					{
						char buffer[FAM_HEADER_LEN+PROTO_CMD_LEN+1];
						PrepareFAMMessage(buffer, FAMMSG_REFUSE);
						SendIMMsg(hContact, buffer, false);
					}
				}
			}
		}
	}
}

bool ProcessContactAck( HANDLE hContact, HANDLE hProcess, bool Success )
{
	TransferSession *session = Sessions::GetInstance().Get(hContact);
	return session && session->ProcessAck(hProcess, Success);
}

void ProcessSendFileQuery( HANDLE hContact )
{
	if (!Sessions::GetInstance().Get(hContact))
	{
		wchar_t filename[2*MAX_PATH] = L"";
		if (SelectFileName(true, filename, sizeof(filename)/sizeof(filename[0])))
		{
			CreateTransferer(hContact, filename);
		}
	}
}
//////////////////////////////////////////////////////////////////////////
// Sender protocol class

DWORD SendSession::min_send_interval = 400;

SendSession::SendSession( HANDLE h_Contact, wchar_t *filename )
: TransferSession(h_Contact, filename, 0), state(0)
{
	//prepare file send request message
	size_t len = sizeof(send_buffer);
	wchar_t *f = wcsrchr(filename, L'\\') + 1;
	char *pos = _utf8encodeW(f?f:filename), *p = strrchr(pos, '?');
	p = p ? p : pos;
	pos = PrepareFAMMessage<FAMMSG_FILE>(send_buffer, len);
	size_t l = strlen(p);
	_ASSERTE(l+24+sizeof(FAM_USERMSG)<len);
	memcpy(pos, p, l);
	_free(p);
	pos[l] = '?';
	pos += l + 1;
	len -= l + 1;
	*(pos++) = ',';--len;//temporary workaround for empty flag set
#pragma warning(suppress:4996)
	_itoa(File->file_size, pos, SIZES_RADIX);
	strcat_s(pos, len, ",");
	l = strlen(pos);
	pos += l;
	len -= l;
#pragma warning(suppress:4996)
	_itoa(File->chunk_size, pos, SIZES_RADIX);
	strcat_s(pos, len, FAM_USERMSG);

	MsgSend(send_buffer, false, true);
}

SendSession::~SendSession( void )
{
}

void SendSession::ProcessMsg( FAMMSGINFO &dbe )
{
	switch (dbe.type)
	{
	case FAMMSG_RESEND:
		Window->SetStatus(LPGENW("Sending missing parts..."), File->SetRepeatList(dbe.pBlob) + 1);
		ProcessSent(true);
		break;
	case FAMMSG_ACCEPT:
		Window->SetStatus(LPGENW("Sending file data..."));
		ProcessSent(true);
		break;
	case FAMMSG_FINISH:
		EndTransfer(true);
		break;
	case FAMMSG_REFUSE:
	case FAMMSG_ABORT:
		state = 3;
		EndTransfer();
		break;
	}
}

void SendSession::ProcessSent( bool timedout )
{
	if (state)
	{
		if (!timedout)
		{
			state = 3;
		}
		EndTransfer();
		return;
	}

	DWORD next_block;
	if (File->GetNext(next_block))
	{
		size_t len = sizeof(send_buffer);
		char *buf = PrepareFAMMessage<FAMMSG_BLOCK>(send_buffer, len);
		if (File->ReadData(buf, len, next_block))
		{
			if (!timedout)
			{
				wtmr.WaitFor(min_send_interval, true);
			}
			MsgSend(send_buffer);
			wtmr.Set(min_send_interval);
			Window->Step();
			return;
		}
	}
	Window->SetStatus(LPGENW("Requesting missing parts..."));
	PrepareFAMMessage(send_buffer, FAMMSG_SENT);
	MsgSend(send_buffer, false);
}

void SendSession::EndTransfer( bool success /*= false*/ )
{
	if (success || state >= 3)
	{
		Window->Hide();
		NBDestroyTransferer(hContact);
		return;
	}
	Window->SetStatus(LPGENW("Aborting..."));
	++state;
	PrepareFAMMessage(send_buffer, FAMMSG_ABORT);
	MsgSend(send_buffer);
}

//////////////////////////////////////////////////////////////////////////
// Receiver protocol class


RecvSession::RecvSession( HANDLE h_Contact, wchar_t *filename, DWORD flags, DWORD filesize, DWORD chunk_size )
: TransferSession(h_Contact, filename, flags, filesize, chunk_size), state(0)
{
	char buffer[FAM_HEADER_LEN+PROTO_CMD_LEN+1];
	PrepareFAMMessage(buffer, FAMMSG_ACCEPT);
	MsgSend(buffer, false);
	Window->SetStatus(LPGENW("Receiving file data..."));
}

RecvSession::~RecvSession( void )
{
}

void RecvSession::ProcessMsg( FAMMSGINFO &dbe )
{
	switch (dbe.type)
	{
	case FAMMSG_BLOCK:
		{
			if (File->WriteData(dbe.pBlob, dbe.cbBlob))
			{
				Window->Step();
			}
		}
		break;
	case FAMMSG_SENT:
		if (!File->GetRepeatList(NULL, 0))
		{
			char buffer[CHUNK_SIZE_MAX];
			size_t len = File->chunk_size;
			File->GetRepeatList(PrepareFAMMessage<FAMMSG_RESEND>(buffer, len), len);
			MsgSend(buffer, false);
			Window->SetStatus(LPGENW("Receiving missing parts..."));
		}
		else
		{
			char buffer[FAM_HEADER_LEN+PROTO_CMD_LEN+1];
			PrepareFAMMessage(buffer, FAMMSG_FINISH);
			MsgSend(buffer, false);
			EndTransfer(true);
		}
		break;
	case FAMMSG_ABORT:
		state = 3;
		EndTransfer();
	}
}

void RecvSession::ProcessSent( bool timedout )
{
	if (state)
	{
		if (!timedout)
		{
			state = 3;
		}
		EndTransfer();
		return;
	}
}

void RecvSession::EndTransfer( bool success /*= false*/ )
{
	if (success || 3 == state)
	{
		File->keep_file = success;
		//File.reset();
		Window->Hide();
		NBDestroyTransferer(hContact);
		return;
	}
	Window->SetStatus(LPGENW("Aborting..."));
	++state;
	char buffer[FAM_HEADER_LEN+PROTO_CMD_LEN+1];
	PrepareFAMMessage(buffer, FAMMSG_ABORT);
	MsgSend(buffer);
}

